﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace Mvc.Models
{
    
    public class MyAuthoirize :AuthorizeAttribute{

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {

            var rd = httpContext.Request.RequestContext.RouteData;
            string currentAction = rd.GetRequiredString("action").ToUpper();
            string currentController = (rd.GetRequiredString("controller")+"CONTROLLER").ToUpper();
            
            string userName=HttpContext.Current.User.Identity.Name;
            UsersContext db = new UsersContext();

            UserProfile user = db.UserProfiles.Single(p => p.UserName == userName);

            var permiso = (from q in db.Permissions
                          where (q.GroupId == user.GroupId) &&
                          (q.Controlador.ToUpper() == currentController) &&
                          (q.Accion.ToUpper() == currentAction)
                          orderby q.PermissionId descending
                          select q).FirstOrDefault() ;
            
            if (permiso ==null)
            {
                return false;
            }
            else {

                if (permiso.Concedido == true)
                {
                    return true;
                }
                else {
                    return false;
                }
                
            }
            
        }


        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (filterContext.Result is HttpUnauthorizedResult && WebSecurity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/Account/AccessDenied");
            }
        }
    
    }






}